package com.tanglongan.concurrent.monitor;

import java.util.concurrent.locks.StampedLock;

public class Point {

    private int x, y;
    final StampedLock sl = new StampedLock();

    double distanceFromPrigin() {
        //乐观读
        long stamp = sl.tryOptimisticRead();
        //读入局部变量，读的过程中数据可能被修改
        int curX = x, curY = y;
        //判断在乐观读操作期间，是否存在写操作，如果存在，则sl.vlidate返回false
        if (!sl.validate(stamp)) {
            //升级为悲观读
            stamp = sl.readLock();
            try {
                curX = x;
                curY = y;
            } finally {
                //释放悲观读
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(curX * curX + curY * curY);
    }

}
